<template>
    <view class="pages">
        <textarea v-model="formData.content" class="content-textarea" placeholder="请输入内容" :maxlength="30000"
            :adjust-position="false" />
        <InputField v-model="formData.count" label="数量" required placeholder="请输入数量" />
        <button @click="onSong">生成歌词</button>

        <view class="tabs-container" v-if="list.length">
            <scroll-view scroll-x class="tabs-scroll">
                <view class="tabs">
                    <view v-for="(item, index) in list" :key="index" class="tab-item"
                        :class="{ active: currentTab === index }" @click="currentTab = index">
                        歌词{{ index + 1 }}
                    </view>
                </view>
            </scroll-view>

            <checkbox-group class="section-toggles">
                <label v-for="section in sections" :key="section.name" class="toggle-item">
                    <checkbox :value="section.name" :checked="section.show" @click="handleSectionToggle(section)" />
                    <text class="checkbox-text">{{ section.label }}</text>
                </label>
            </checkbox-group>

            <view class="checkbox-group">
                <template v-for="section in sections" :key="section.name">
                    <view v-if="section.show" class="checkbox-section">
                        <text class="section-title">{{ section.label }}</text>
                        <label v-for="(item, index) in list[currentTab]?.[section.name]" :key="index"
                            class="checkbox-item">
                            <text class="checkbox-text">{{ item }}</text>
                            <button class="edit-btn" @click.stop="showEdit(section.name, index)">
                                <image src="/static/icons/add.png" class="edit-icon" />
                            </button>
                        </label>
                    </view>


                </template>
            </view>

        </view>
        <!-- 编辑弹窗 -->
        <uni-popup ref="popup" type="dialog">
            <view class="edit-popup">
                <view class="popup-title">编辑内容</view>
                <textarea v-model="editContent" class="edit-textarea" :adjust-position="false" placeholder="请输入内容" />
                <view class="popup-btns">
                    <button class="btn cancel" @click="hideEdit">取消</button>
                    <button class="btn confirm" @click="confirmEdit">确定</button>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script setup>
import { reactive, ref, watch } from 'vue'
import InputField from '@/components/InputField.vue'
import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue'
const token = 'pat_hDLUMqRTuu6iyZo25QTCKqK07KkRwh6JiQiroJZSUqdKlDnwrMF6PE1LI5POPB70'; //2025/3/1过期
const workflow_id = '7466775571867959346';
// const formData = reactive({
//     count: '',
//     content: '',
// })
// 定义工作流接口的 URL
const url = `https://api.coze.cn/v1/workflow/run`;

// 定义请求头
const headers = {
    'Content-Type': 'application/json', // 设置请求体为 JSON 格式
    'Authorization': `Bearer ${token}`, // 替换为你的访问令牌
};
const list = ref([])
const currentTab = ref(0)

const sections = reactive([
    // { name: 'duration', label: '时长', show: true },
    // { name: 'scene', label: '场景', show: true },
    { name: 'word', label: '歌词', show: true },
    { name: 'desc', label: '描述', show: true },
])


// 编辑相关的状态
const popup = ref(null)
const editContent = ref('')
const currentEdit = ref({
    section: '',
    index: -1
})

// 显示编辑弹窗
const showEdit = (section, index) => {
    currentEdit.value = { section, index }
    editContent.value = list.value[currentTab.value][section][index]
    // 确保 popup 已经挂载
    setTimeout(() => {
        if (popup.value) {
            popup.value.open('center')
        }
    }, 30)
}

// 修改隐藏编辑弹窗方法
const hideEdit = () => {
    if (popup.value) {
        popup.value.close()
    }
    editContent.value = ''
    currentEdit.value = { section: '', index: -1 }
}

// 确认编辑
const confirmEdit = () => {
    const { section, index } = currentEdit.value
    if (section && index > -1) {
        list.value[currentTab.value][section][index] = editContent.value
    }
    hideEdit()
}

// 处理复选框变化
const handleSectionToggle = (section) => {
    section.show = !section.show
}

// 监听list变化，自动切换到最新tab
watch(() => list.value.length, (newLength) => {
    if (newLength > 0) {
        currentTab.value = newLength - 1
    }
})

async function loadData() {
    try {
        const body = {
            parameters: {
                input: formData.content,
            },
            workflow_id: workflow_id,
            is_async: false,
        }

        const response = await uni.request({
            url: url,
            method: 'POST',
            header: headers,
            data: body,
        })

        if (response.statusCode !== 200) {
            throw new Error(`HTTP error! status: ${response.statusCode}`)
        }

        const obj = response.data
        console.log("###", obj)
        const aim = JSON.parse(obj.data)
        console.log("#---#", aim)

        list.value.push({
            word: aim.word,
            desc: aim.desc.map((item, i) => {
                return `${item} (${aim.scene[i]} | ${aim.duration[i]})`
            })
        })

    } catch (error) {
        console.error('Error:', error)
        uni.showToast({
            title: '请求失败',
            icon: 'none'
        })
    }
}

// 从本地存储读取数据
const initFormData = () => {
    try {
        const savedData = uni.getStorageSync('cozeFormData')
        if (savedData) {
            return JSON.parse(savedData)
        }
    } catch (e) {
        console.error('读取本地数据失败:', e)
    }
    return {
        count: '',
        content: '',
    }
}

const formData = reactive(initFormData())

// 保存数据到本地存储
const saveFormData = () => {
    try {
        uni.setStorageSync('cozeFormData', JSON.stringify(formData))
    } catch (e) {
        console.error('保存数据失败:', e)
    }
}

// 修改 onSong 函数
async function onSong() {
    const count = Number(formData.count)
    if (count > 0) {
        saveFormData() // 保存表单数据
        for (let i = 0; i < count; i++) {
            setTimeout(() => {
                loadData()
            }, i * 2000)
        }
    } else {
        uni.showToast({
            title: '请输入大于0的数字',
            icon: 'none'
        })
    }
}
</script>

<style lang="scss" scoped>
.pages {
    padding: 30rpx;
    display: flex;
    flex-direction: column;
    gap: 30rpx;
}

.section-toggles {
    margin: 40rpx 0;
    display: flex;
    gap: 40rpx;
}

.tabs-container {
    margin-top: 20rpx;
}

.tabs-scroll {
    white-space: nowrap;
    border-bottom: 1px solid #eee;
}

.tabs {
    display: inline-flex;
    padding: 0 20rpx;
}

.tab-item {
    padding: 20rpx 30rpx;
    font-size: 28rpx;
    color: #666;
    position: relative;

    &.active {
        color: #409eff;

        &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 20rpx;
            right: 20rpx;
            height: 4rpx;
            background: #409eff;
            border-radius: 2rpx;
        }
    }
}

.tab-content {
    padding: 20rpx;

    .content-item {
        font-size: 28rpx;
        line-height: 1.6;
        white-space: pre-wrap;
    }
}

.tabs-container {
    margin-top: 20rpx;
}

.tabs-scroll {
    white-space: nowrap;
    border-bottom: 1px solid #eee;
}

.tabs {
    display: inline-flex;
    padding: 0 20rpx;
}

.tab-item {
    padding: 20rpx 30rpx;
    font-size: 28rpx;
    color: #666;
    position: relative;

    &.active {
        color: #409eff;

        &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 20rpx;
            right: 20rpx;
            height: 4rpx;
            background: #409eff;
            border-radius: 2rpx;
        }
    }
}

.tab-content {
    padding: 20rpx;

    .content-item {
        font-size: 28rpx;
        line-height: 1.6;
        white-space: pre-wrap;
    }
}

.checkbox-group {
    padding: 20rpx;
}

.checkbox-section {
    margin-bottom: 30rpx;

    .section-title {
        display: block;
        font-size: 28rpx;
        font-weight: bold;
        margin-bottom: 16rpx;
        color: #333;
    }
}

.checkbox-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 16rpx;

    .checkbox-text {
        font-size: 26rpx;
        color: #666;
        margin-left: 12rpx;
        line-height: 1.4;
    }
}

.checkbox-item {
    position: relative;
    padding-right: 80rpx;

    .edit-btn {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 60rpx;
        height: 60rpx;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background: none;
        border: none;

        &::after {
            display: none;
        }

        .edit-icon {
            width: 32rpx;
            height: 32rpx;
            opacity: 0.6;
        }
    }
}

.edit-popup {
    background: #fff;
    border-radius: 24rpx;
    padding: 30rpx;
    width: 600rpx;

    .popup-title {
        font-size: 32rpx;
        font-weight: bold;
        text-align: center;
        margin-bottom: 30rpx;
    }

    .edit-textarea {
        width: 100%;
        height: 300rpx;
        border: 2rpx solid #dcdfe6;
        border-radius: 12rpx;
        padding: 20rpx;
        font-size: 28rpx;
        margin-bottom: 30rpx;
    }

    .popup-btns {
        display: flex;
        gap: 20rpx;

        .btn {
            flex: 1;
            height: 80rpx;
            line-height: 80rpx;
            text-align: center;
            border-radius: 8rpx;
            font-size: 28rpx;

            &.cancel {
                background: #f5f7fa;
                color: #666;
            }

            &.confirm {
                background: #409eff;
                color: #fff;
            }
        }
    }
}

.checkbox-item {
    position: relative;
    padding-right: 80rpx;

    .edit-btn {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 60rpx;
        height: 60rpx;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background: none;
        border: none;

        &::after {
            display: none;
        }

        .edit-icon {
            width: 32rpx;
            height: 32rpx;
            opacity: 0.6;
        }
    }
}

.edit-popup {
    background: #fff;
    border-radius: 24rpx;
    padding: 30rpx;
    width: 600rpx;

    .popup-title {
        font-size: 32rpx;
        font-weight: bold;
        text-align: center;
        margin-bottom: 30rpx;
    }

    .edit-textarea {
        width: 100%;
        height: 300rpx;
        border: 2rpx solid #dcdfe6;
        border-radius: 12rpx;
        padding: 20rpx;
        font-size: 28rpx;
        margin-bottom: 30rpx;
    }

    .popup-btns {
        display: flex;
        gap: 20rpx;

        .btn {
            flex: 1;
            height: 80rpx;
            line-height: 80rpx;
            text-align: center;
            border-radius: 8rpx;
            font-size: 28rpx;

            &.cancel {
                background: #f5f7fa;
                color: #666;
            }

            &.confirm {
                background: #409eff;
                color: #fff;
            }
        }
    }
}
</style>